const express = require('express');
const router = express.Router();
const productController = require('../controllers/productController');
const auth = require('../middleware/authMiddleware');
const multer = require('multer');
const path = require('path');
const authMiddleware = require('../middleware/authMiddleware');

// 商品图片上传配置
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, path.join(__dirname, '../../uploads/products'));
  },
  filename: function (req, file, cb) {
    const ext = path.extname(file.originalname);
    cb(null, 'product_' + req.user.user_id + '_' + Date.now() + ext);
  }
});

// 文件数量验证中间件
const validateImageCount = (req, res, next) => {
  if (req.files && req.files.length > 10) {
    return res.status(400).json({
      message: '上传图片数量不能超过10张'
    });
  }
  next();
};

const upload = multer({ storage });

// 获取所有商品分类（父子结构）
router.get('/categories', productController.getAllCategories);

// 获取用户发布商品的分类（需认证）
router.get('/my/categories', authMiddleware, productController.getUserCategories);

// 获取用户发布的商品（需认证）
router.get('/my', authMiddleware, productController.getMyProducts);

// 发布商品（需认证+多图片上传）
router.post('/create', authMiddleware, upload.array('images', 10), validateImageCount, productController.createProduct);

// 按条件筛选商品
router.get('/filter',authMiddleware, productController.filterProducts);

// 获取热门商品
router.get('/hot', productController.getHotProducts);

// 删除商品（需认证）
router.delete('/:id', authMiddleware, productController.deleteProduct);

// 更新商品状态（需认证）
router.put('/:id/status', authMiddleware, productController.updateProductStatus);

// 更新商品（需认证+多图片上传可选）
router.put('/:id', authMiddleware, upload.array('images', 10), validateImageCount, productController.updateProduct);

// 获取商品详情
router.get('/:id', productController.getProductDetail);

module.exports = router;
